{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ZOWgx2fYqW8T"
   },
   "source": [
    "# GitHub Repository Insights with PraisonAIAgents"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "XgJdLRiIqZ2L"
   },
   "source": [
    "This notebook demonstrates how to explore and analyze GitHub repositories using PraisonAIAgents in Google Colab. You can query repository issues, pull requests, and activity patterns with natural language, leveraging the power of agentic tools—all without leaving your notebook."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Y_koMT6qzxne"
   },
   "source": [
    "[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Dhivya-Bharathy/PraisonAI/blob/main/examples/cookbooks/Programming_Code_Analysis_Agents/GitHub_Repository_Insights.ipynb)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "2ey7zWAJrIPx"
   },
   "source": [
    "# Dependencies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "id": "_xFH-iLTxzd8"
   },
   "outputs": [],
   "source": [
    "!pip install praisonaiagents openai requests --quiet"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Kzty0zxzsbZ_"
   },
   "source": [
    "# Set Up Key"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "id": "HCVP5fmvx2hH"
   },
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "# Set your GitHub token here\n",
    "GITHUB_TOKEN = \"your-github-token\"  # <-- Replace with your actual token\n",
    "\n",
    "# Set your OpenAI API key here (required by PraisonAIAgents, even if not used for LLM)\n",
    "OPENAI_API_KEY = \"your-openai-api-key\"  # <-- Replace with your actual OpenAI API key\n",
    "\n",
    "# Set environment variable for OpenAI\n",
    "os.environ[\"OPENAI_API_KEY\"] = OPENAI_API_KEY"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "10BTLbF4s_f-"
   },
   "source": [
    "# Import Libraries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "id": "_sLahvfXyEb0"
   },
   "outputs": [],
   "source": [
    "from praisonaiagents import Agent\n",
    "import requests\n",
    "from IPython.display import display, Markdown"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "GRftdghxtUDs"
   },
   "source": [
    "# Custom Tool"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "id": "nT11EFNNyIHl"
   },
   "outputs": [],
   "source": [
    "def github_query_tool(query: str, repo: str, github_token: str) -> str:\n",
    "    \"\"\"\n",
    "    Custom tool to query GitHub repository data using the GitHub API.\n",
    "    Supports basic queries for issues, pull requests, and repository info.\n",
    "    \"\"\"\n",
    "    headers = {\n",
    "        \"Authorization\": f\"token {github_token}\",\n",
    "        \"Accept\": \"application/vnd.github.v3+json\"\n",
    "    }\n",
    "    base_url = f\"https://api.github.com/repos/{repo}\"\n",
    "    result = \"\"\n",
    "\n",
    "    if \"issue\" in query.lower():\n",
    "        url = f\"{base_url}/issues\"\n",
    "        response = requests.get(url, headers=headers)\n",
    "        if response.ok:\n",
    "            issues = response.json()\n",
    "            result = f\"Found {len(issues)} issues in {repo}.\\n\"\n",
    "            for issue in issues[:5]:\n",
    "                result += f\"- #{issue['number']}: {issue['title']} (State: {issue['state']})\\n\"\n",
    "        else:\n",
    "            result = f\"Failed to fetch issues: {response.text}\"\n",
    "\n",
    "    elif \"pull request\" in query.lower() or \"pr\" in query.lower():\n",
    "        url = f\"{base_url}/pulls\"\n",
    "        response = requests.get(url, headers=headers)\n",
    "        if response.ok:\n",
    "            pulls = response.json()\n",
    "            result = f\"Found {len(pulls)} pull requests in {repo}.\\n\"\n",
    "            for pr in pulls[:5]:\n",
    "                result += f\"- #{pr['number']}: {pr['title']} (State: {pr['state']})\\n\"\n",
    "        else:\n",
    "            result = f\"Failed to fetch pull requests: {response.text}\"\n",
    "\n",
    "    elif \"activity\" in query.lower() or \"stats\" in query.lower():\n",
    "        url = f\"{base_url}/stats/contributors\"\n",
    "        response = requests.get(url, headers=headers)\n",
    "        if response.ok:\n",
    "            stats = response.json()\n",
    "            result = f\"Repository activity for {repo}:\\n\"\n",
    "            for contributor in stats[:5]:\n",
    "                result += f\"- {contributor['author']['login']}: {contributor['total']} commits\\n\"\n",
    "        else:\n",
    "            result = f\"Failed to fetch activity stats: {response.text}\"\n",
    "\n",
    "    else:\n",
    "        # Default: basic repo info\n",
    "        response = requests.get(base_url, headers=headers)\n",
    "        if response.ok:\n",
    "            info = response.json()\n",
    "            result = (\n",
    "                f\"Repository: {info['full_name']}\\n\"\n",
    "                f\"Description: {info.get('description', 'No description')}\\n\"\n",
    "                f\"Stars: {info['stargazers_count']}\\n\"\n",
    "                f\"Forks: {info['forks_count']}\\n\"\n",
    "                f\"Open Issues: {info['open_issues_count']}\\n\"\n",
    "            )\n",
    "        else:\n",
    "            result = f\"Failed to fetch repository info: {response.text}\"\n",
    "\n",
    "    return result"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "mAFg5SW-tacD"
   },
   "source": [
    "#  Register Tool and Create Agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "id": "x_MmUc_AyMaB"
   },
   "outputs": [],
   "source": [
    "def github_tool_wrapper(inputs):\n",
    "    query = inputs.get(\"query\", \"\")\n",
    "    repo = inputs.get(\"repo\", \"\")\n",
    "    github_token = inputs.get(\"github_token\", \"\")\n",
    "    return github_query_tool(query, repo, github_token)\n",
    "\n",
    "agent = Agent(\n",
    "    instructions=\"\"\"\n",
    "    You are a GitHub assistant. Help users explore repositories and their activity.\n",
    "    - Provide organized, concise insights about the repository.\n",
    "    - Focus on facts and data from the GitHub API.\n",
    "    - Use markdown formatting for better readability.\n",
    "    - Present numerical data in tables when appropriate.\n",
    "    - Include links to relevant GitHub pages when helpful.\n",
    "    \"\"\",\n",
    "    tools={\n",
    "        \"github_query_tool\": github_tool_wrapper\n",
    "    }\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "lPstz7bbtr0k"
   },
   "source": [
    "# User Input and Run Agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 118
    },
    "id": "MymtRmlnyQqd",
    "outputId": "33a23810-4a67-4615-f9e9-146b3030fcbf"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Enter the GitHub repository (owner/repo): Dhivya-Bharathy/PraisonAI\n",
      "Enter your question (e.g., Show me open issues): Show me open issues\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "### Results\n",
       "Found 0 issues in Dhivya-Bharathy/PraisonAI.\n"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# User input\n",
    "repo = input(\"Enter the GitHub repository (owner/repo): \")\n",
    "query = input(\"Enter your question (e.g., Show me open issues): \")\n",
    "\n",
    "# Call the tool directly (since agent.chat expects an LLM, but we want tool output)\n",
    "response = agent.execute_tool(\"github_query_tool\", {\n",
    "    \"query\": query,\n",
    "    \"repo\": repo,\n",
    "    \"github_token\": GITHUB_TOKEN\n",
    "})\n",
    "\n",
    "# Display the result\n",
    "display(Markdown(f\"### Results\\n{response}\"))"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
